package com.queclink.ycm.tcp;


import com.queclink.ycm.codec.MessageDecoder;
import com.queclink.ycm.handler.GatewayInBoundHandler;
import com.queclink.ycm.handler.GatewayOutBoundHandler;
import com.sun.media.jfxmedia.logging.Logger;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.LoggerFactory;

import java.util.HashMap;


/**
 * @author jim.li
 * @email jim.li@queclink.com
 * @date 2022-01-09 11:44:00
 */
public class GatewayTcpServer {

    private static org.slf4j.Logger logger = LoggerFactory.getLogger(GatewayTcpServer.class);

    public static HashMap<Integer, Channel> serverChannel = new HashMap<>();

//    private static Channel serverChannel;




    public void startup(int port) {
        // 服务器线程组 用于网络事件的处理 一个用于服务器接收客户端的连接
        // 另一个线程组用于处理SocketChannel的网络读写
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            ServerBootstrap bo = new ServerBootstrap().group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 100)
                    .option(ChannelOption.SO_REUSEADDR, true)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    .addLast(new IdleStateHandler(900, 0, 0))
                                    .addLast(new ByteArrayEncoder())
                                    .addLast(new MessageDecoder())
                                    .addLast(new GatewayOutBoundHandler())
                                    .addLast(new GatewayInBoundHandler(port));
                        }
                    });
            ChannelFuture f = bo.bind(port).sync();// 绑定端口，开始接收进来的连接
            serverChannel.put(port, f.channel());
            System.out.println("TCP Server [" + port + "] started success.");
            // 监听服务器关闭监听
            f.channel().closeFuture().sync();
        } catch (Exception e) {

        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }


    public static void closeServer(int port) {
        if (serverChannel.get(port) != null) {
            logger.info("close server");
            serverChannel.get(port).close();
            serverChannel.put(port, null);
        }
    }
}
